package com.rongke.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.model.*;
import com.rongke.service.GoodsService;
import com.rongke.service.PanicBuyingGoodsService;
import com.rongke.service.PanicBuyingTimeService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @version : Ver 1.0
 * @PanicBuyingGoodsController
 * @商品抢购Controller
 */
@RestController
@RequestMapping(value = "/api/panicBuyingGoods")
@Transactional
@CrossOrigin(origins = "*", maxAge = 3600)
public class PanicBuyingGoodsController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private PanicBuyingGoodsService panicBuyingGoodsService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private PanicBuyingTimeService panicBuyingTimeService;

    /**
     * @param panicBuyingGoods
     * @return 返回值JsonResp
     * @添加商品抢购
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResp addPanicBuyingGoods(@RequestBody PanicBuyingGoods panicBuyingGoods) {
        log.debug("添加商品抢购");
        panicBuyingGoodsService.insert(panicBuyingGoods);
        return JsonResp.ok(panicBuyingGoods);
    }

    /**
     * @param pbList
     * @return
     * @批量添加今日特卖
     */
    @RequestMapping(value = "/addTodayBuyingGoodsBatch", method = RequestMethod.POST)
    public JsonResp addTodayBuyingGoodsBatch(@RequestBody List<PanicBuyingGoods> pbList) {
        log.debug("批量添加今日特卖");
        if (null == pbList || pbList.size() == 0)
            return JsonResp.toFail("server:添加的今日特卖商品不能为空");
        panicBuyingGoodsService.insertBatch(pbList);
        return JsonResp.ok(pbList);
    }


    /**
     * @param panicBuyingGoods
     * @return 返回值JsonResp
     * @修改商品抢购
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResp updatePanicBuyingGoods(@RequestBody PanicBuyingGoods panicBuyingGoods) {
        log.debug("修改商品抢购");
        panicBuyingGoodsService.updateById(panicBuyingGoods);
        return JsonResp.ok(panicBuyingGoods);
    }

    /**
     * 批量更新今日特卖商品
     * @param pbList
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/uptTodayBuyingBatch", method = RequestMethod.POST)
    public JsonResp uptTodayBuyingBatch(@RequestBody List<PanicBuyingGoods> pbList) {
        log.debug("批量更新今日特卖商品");
        if(pbList.size()==0)
            return JsonResp.toFail("server:添加的抢购商品为空！");
        panicBuyingGoodsService.updateBatchById(pbList);
        return JsonResp.ok(pbList);
    }

    /**
     * @根据时间段id删除时间段和时间段内所有商品
     * @return
     */
    @RequestMapping(value = "/delAllPanicBuyingByDurationId", method = RequestMethod.GET)
    public JsonResp delAllPanicBuyingByDurationId(Long pbtId){
        log.debug("根据时间段id删除时间段和时间段内所有商品");
        if(null==pbtId)
            return JsonResp.toFail("参数不能为空");
        EntityWrapper<PanicBuyingGoods> ew=new EntityWrapper<>();
        ew.eq("pbt_id",pbtId);
        panicBuyingGoodsService.delete(ew);
        /*先删除时间段会报外键约束错误*/
        EntityWrapper<PanicBuyingTime> ewt=new EntityWrapper<>();
        ewt.eq("id",pbtId);
        panicBuyingTimeService.delete(ewt);
        return JsonResp.ok("");
    }

    /**
     * @param pbList
     * @return
     * @批量删除今日特卖
     */
    @RequestMapping(value = "/deleteTodayBuyingGoodsBatch", method = RequestMethod.POST)
    public JsonResp deleteTodayBuyingGoodsBatch(@RequestBody List<PanicBuyingGoods> pbList) {
        log.debug("批量删除今日特卖");
        if (null == pbList || pbList.size() == 0)
            return JsonResp.toFail("server:要删除的今日特卖商品不能为空");
        for (PanicBuyingGoods pb : pbList) {
            EntityWrapper<PanicBuyingGoods> ew = new EntityWrapper<>(pb);
            panicBuyingGoodsService.delete(ew);
        }
        return JsonResp.ok(pbList);
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @根据id查找商品抢购
     */
    @RequestMapping(value = "/selectOne", method = RequestMethod.GET)
    public JsonResp selectPanicBuyingGoods(Long id) {
        log.debug("查找商品抢购");

        PanicBuyingGoods panicBuyingGoods = panicBuyingGoodsService.selectById(id);
        return JsonResp.ok(panicBuyingGoods);
    }


    /**
     * @param pbtId 抢购日期id
     * @return 返回值JsonResp
     * @主页获取抢购商品列表
     */
    @RequestMapping(value = "/selectIndexPanicBuyingGoodsList", method = RequestMethod.GET)
    public JsonResp selectIndexPanicBuyingGoodsList(Long pbtId) {
        log.debug("查找限时抢购商品");
        List<PanicBuyingGoods> panicBuyingGoods = panicBuyingGoodsService.selectIndexPanicBuyingGoodsList(pbtId);
        if(!panicBuyingGoods.isEmpty()){
            panicBuyingGoods.forEach(e->{
                goodsService.fetchGoodsInventoryStatus(e.getGoods());//判断库存状态
            });
        }
        EntityWrapper<PanicBuyingTime> ew = new EntityWrapper<>();
        String sdf=new SimpleDateFormat("yyyy-MM-dd").format(new Date())+" 23:59:59";
        Date date=null;
        try {
            date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        ew.le("start_date",date);
        List<PanicBuyingTime> panicBuyingTimeList = panicBuyingTimeService.selectList(ew);
        Map map = new HashMap();
        int  y = panicBuyingTimeList.size();
        //如果查询日期列表中有今日的日期  显示今日的日期
        for (int m=0;m<y;m++) {
            PanicBuyingTime current=panicBuyingTimeList.get(m);
            String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            if ( currentDate.compareTo(new SimpleDateFormat("yyyy-MM-dd").format(current.getEndDate())) <= 0){
                if(m<y-1){
                    PanicBuyingTime nest=panicBuyingTimeList.get(m+1);
                    if(new SimpleDateFormat("HH:mm").format(new Date()).compareTo(new SimpleDateFormat("HH:mm").format(current.getStartDate()))<0){
                        current.setStatus("未开始");
                    }else if(new SimpleDateFormat("HH:mm").format(new Date()).compareTo(new SimpleDateFormat("HH:mm").format(nest.getStartDate()))>=0){
                        current.setStatus("已结束");
                    }else {
                        current.setStatus("抢购中");
                    }
                }
                if(m==y-1){
                    if(new SimpleDateFormat("HH:mm").format(new Date()).compareTo(new SimpleDateFormat("HH:mm").format(current.getStartDate()))<0){
                        current.setStatus("未开始");
                    }else if(new SimpleDateFormat("HH:mm").format(new Date()).compareTo(new SimpleDateFormat("HH:mm").format(current.getStartDate()))>=0){
                        current.setStatus("抢购中");
                    }
                }
            }else {
                current.setStatus("已结束");
            }

            if(current.getId()==pbtId){
                current.setPanicBuyingGoodses(panicBuyingGoods);
                map.put("panicBuyingTime", current);
                break;
            }
        }

        return JsonResp.ok(map);
    }




    /**
     * 后台蜜哆哆今日特卖分页获取可添加的商品(可按商品分类，分组等)
     *
     * @param goodsPage
     * @return
     */
    @RequestMapping(value = "/getUnPanicedGoodsListWithCategory", method = RequestMethod.POST)
    public JsonResp getUnPanicedGoodsListWithCategory(@RequestBody GoodsPage goodsPage) {
        log.debug("后台蜜哆哆今日特卖分页获取可添加的商品(可按商品分类，分组等)");
        Goods goods = goodsPage.getGoods();
        Page page = goodsPage.getPage();
        if (null == page)
            return JsonResp.toFail("参数不能为空");

        EntityWrapper<Goods> ew = new EntityWrapper<>();
        //已发布的该产品线（蜜哆哆 0）下在售的商品
        ew.eq("goods_status", 2)
                .eq("goods_type", 0);
        if (null != goods.getClassifyId())
            ew.eq("classify_id", goods.getClassifyId());
        if (null != goods.getIndexGroupId())
            ew.eq("index_group_id", goods.getIndexGroupId());

/*        //排除已添加的商品,参考添加推荐
        EntityWrapper<GoodsRecommend> ewgr = new EntityWrapper();
        ewgr.eq("goods_id", goods.getId());
        //先从推荐表获取推荐商品列表
        List<GoodsRecommend> recommendList =goodsRecommendService.selectList(ewgr);
        if (recommendList.size() > 0){
            List<Long> idList = new ArrayList<>();
            //取出推荐商品的id集合
            for (GoodsRecommend rec : recommendList) {
                if(null!=rec.getRecGoodsId())
                    idList.add(rec.getRecGoodsId());
            }
            ew.notIn("id",idList);
        }*/

        //搜索
        if (null != goodsPage.getSearchText())
            ew.like("goods_name", goodsPage.getSearchText());
        Page<Goods> gdPage = goodsService.selectPage(page, ew);
        gdPage.setOrderByField("classify_id");
        return JsonResp.ok(gdPage);
    }


    /**
     * @param goodsPage
     * @return
     * @根据抢购时间段id分页获取已添加的抢购商品信息
     */
    @RequestMapping(value = "/getPanicedGoodsPageWithDurationId", method = RequestMethod.POST)
    public JsonResp getPanicedGoodsPageWithDurationId(@RequestBody GoodsPage goodsPage) {
        log.debug("根据抢购时间段id分页获取已添加的抢购商品信息");
        Integer durationId = goodsPage.getIntParam();
        if (null == durationId) {
            return JsonResp.toFail("server:抢购时段参数不能为空");
        }
        Page page = goodsPage.getPage();
        if (null == page) {
            return JsonResp.toFail("server:page参数不能为空");
        }
        Map map = new HashMap();
        map.put("durationId", durationId);
        Integer startIndex = page.getSize() * (page.getCurrent() - 1);
        Integer size=page.getSize();
        map.put("startIndex", startIndex);
        map.put("size",size);
        List<PanicBuyingGoodsCombineGoods> pgList = panicBuyingGoodsService.selectLimitedPGListByDurationId(map);
        page.setRecords(pgList);
        //查出total
        EntityWrapper<PanicBuyingGoods> ew=new EntityWrapper<>();
        ew.eq("pbt_id",durationId);
        List<PanicBuyingGoods> totalList=panicBuyingGoodsService.selectList(ew);
        int total=totalList.size();
        int pagesNum=total/size;
        if(total%size!=0) {
            pagesNum+=1;
        }
        page.setTotal(total);
        return JsonResp.ok(page);

    }

}
